7.4 What and how to control, and event-driven programming

  1. Motivations
  2. Events and event driven programming
    • In the previous two assignments, you can select the board size and click the button to start the game.
    • In this image, event emitters are HTML elements in the body. For example, when the user clicks an element, the 'click' event is emitted from the element. In another word, the 'click' event is triggered on the element. Then the event listener (oac handler), which is usually a function and registered for the 'click' event on the element, will be invoked.
    • The question is, when the user can trigger events on HTML elements, which event listeners should be executed? Who provides the event listeners?
    • Before we discuss the above questions, what kind of events do you think you need?
      • Mouse events - click, mouseover, mouseout, ...
      • Key events - keydown, keyup, ...
      • Window events - ...
      • ...
    • Read all in JavaScript Events.
      • Did you do the exercises at the bottom in the above link?
      • List all the common events explained.
      • What can you do with JavaScript and events?
      • Explain how the onclick attribute is used. You have seen many examples.
      • Trial 1: Let's try to display date and time. When a button is clicked, a <p> is updated.


      • Trial 2: Let's try to change the background color to 'LightBlue' when the mouse moves over a <div> box. You need to use the two mouse events, not the CSS hover pseudo class.


    • Read all in JavaScript HTML DOM Events.
      • Did you do the exercises at the bottom in the above link?
      • Can you write the code for the first example?
      • How to register event listeners?
      • What is 'this' in the second example?
      • In the second example, can you add some code so that the button has the original string value when it is clicked again?
      • How to access/control/update HTML elements?
      • On what elements is the 'load' event triggered?
      • What is the 'change' event triggered? What elements trigger this event?
      • On what elements are the 'mouseover', 'mouseout', 'mousedown', 'mouseup' and 'click' events triggered?
      • Trial 3: Let's try to change the HTML content when the element is clicked. You can use 'this'.


    • Can you list all the events that you have studied so far?    click, load, change, mouseover, mouseout, mousedown, mouseup
    • There are three event registration models, as follows.
    • The inline event registration model
      • In this model, The invocation of an event listener is registered as inline event attribute value, and some arguments can be passed.
      • We have used this model so far.
    • The W3C event registration model - Read all in JavaScript HTML DOM EventListener.
      • Can you register multiple event listeners?
      • On what object is the 'resize' event triggered?
      • How to remove an event listener?
      • What are the advantages of using this model?    Multiple event listeners, better readability, easy removal of event listeners, ...
      • Trial 4: Let's try to change the HTML content when the element is clicked. You SHOULD use the W3C event registration model, not the inline model.


      • Trial 4-5: Let's try the above example again. Does it work correctly? What happens?
    • The traditional event registration model.
      • Event properties - onclick, onload, onmouseover, onmouseout, onchange, onresize, ...
      • Syntax: In <script>, elementobject.eventproperty = eventlistener;
      • Here is an example.
        <body>
            <button id='button'>Click Me!</button> <!-- There is no invocation of event listener here. -->
            <h id='demo'></h>
        
            <script>
                function clickme() {
                    document.getElementById('demo').innerHTML = 'Hmmm';
                }
                document.getElementById('button').onclick = clickme;
            </script>
        </body>
        
      • What if the script in the above example is before the button?
      • Trial 5: Let's try to change the HTML content when the element is clicked. In this exercise, you are asked to use the traditional event registration model.


    • One programming style is ...
      • One programming style is to keep the JavaScript code in <head>, as follows.
        <head>
            <style>
                ...
            </style>
            <script>
                ...
            </script>
        </head>
        <body>
            ...
        </body>
        
      • But, try the next example with runcode.
        <head>
            <script>
                // The W3C model
                function clickme() {
                    document.getElementById('demo').innerHTML = 'Hmmm';
                }
                document.getElementById('button').addEventListener('click', clickme);  // NOT the invocation of an event listener
        
                /* Or the traditional model
                function clickme() {
                    document.getElementById('demo').innerHTML = 'Hmmm';
                }
                document.getElementById('button').onclick = clickme;  // NOT the invocation of an event listener
                */
                /* Or
                document.getElementById('button').onclick = function() {  // Anonymouse function - a function that has no name
                    document.getElementById('demo').innerHTML = 'Hmmm';
                }
                */
            </script>
        </head>
        <body>
            <button id='button'>Click Me!</button> <!-- There is no invocation of event listener here. -->
            <p id='demo'></p>
        </body>
        
      • What is wrong with the above example?
        • <script> is executed before <body>. That is, the element of 'button' is undefined in <script>.
        • What are you supposed to do then?
        • document.getElementById('button').addEventListener(...); should be executed after <body> is completed loaded.
        • Now the question is how do you know whether <body> is completed loaded? Any related event?
      • Try the next example with runcode again.
        <head>
            <script>
                function clickme() {
                        document.getElementById('demo').innerHTML = 'Hmmm';
                }
                function start() {
                    document.getElementById('button').addEventListener('click', clickme);  // NOT the invocation of an event listener
                }
                window.addEventListener('load', start);  // This event is triggered when the <body> is completely loaded.
                                                         // The second argument is NOT the invocation of an event listener.
                /* OR
                window.addEventListener('???', ???() {
                    document.getElementById('button').addEventListener('click', clickme);
                }); 
                */
            </script>
        </head>
        <body>
            <button id='button'>Click Me!</button> <!-- There is no invocation of event listener here. -->
            <p id='demo'></p>
        </body>
        
      • Another programming style is to keep the JavaScript code after <body>, as follows.
        <head>
            <style>
                ...
            </style>
        </head>
        <body>
            ...
        </body>
        <script>
            ...
        </script>
        
    • Can you rewrite all the examples in JavaScript HTML DOM EventListener, so that you can use the above better programming style?
  3. The Event object
    • Here is an example how to use the Event object. From the Event object, we can obtain additional information, such as mouse coordinates and key values.
      document.getElementById('control').addEventListener('click', eh);
      function eh(eobj) {  // eobj is an Event object. The browser invokes this function with the Event object.
          eobj.target.innerHTML = 'Hmmm';  // target: the element object on which this event is triggered.
      }
      
    • List of events - Read all in HTML DOM Events.
    • How to get the key value when a key is pressed?    eventObj.key
    • How to get the position of the mouse pointer?    eventObj.clientX, event.clientY
    • Trial 7: Let's try to capture the mouse position. Which Event properties do you need to use? You are asked to use the W3C event registration model.


    • Trial 8: Let's try to capture the window size. What event do you need to use? You can use innerWidth and innerHeight properties in the window object.


    • How to get the id of the event target object?    eventObj.target.id
  4. Document Object Model (DOM)
    • The HTML DOM is a data structure that includes everything in a web document as a node (a name in the DOM data structure). An object will be created in JS for each node.
    • Read all in The HTML DOM Document Object.
      • What is the document object?
      • What methods in the document object have you used?    write(), getElementById(), addEventListener()
      • Some interesting properties - body, title, URL, ...
    • What is the general procedure to control HTML and CSS with JS?    Event -> Obtain HTML/CSS objects. --> Update or use their properties and methods.
    • How to get elements by tag name? Read all in HTML DOM getElementsByTagName() Method.
    • Trial 12: Let's try to change the background color of all <p> elements.


    • How to get elements by class name? Read all in HTML DOM getElementsByClassName() Method.
    • How to get elements by CSS selector? Read all in HTML DOM querySelectorAll() Method.
    • Trial 13: Let's try to change the background color of all <p> elements that belong to class 'tr13'.


    • How to control attributes of an element?    elementobj.attributename, elementobj.getAttribute(name), elementobj.setAttribute(name, value)
    • How to control CSS styles (i.e., CSS properties) of an element?    elementobj.style.csspropertyname, elementobj.style.getProperty(name), elementobj.style.setProperty(name, value)
  5. Browser Object Model (BOM)
    • The window object represents an open window in a browser. This object supports many useful properties and methods.
    • Read all in The Window Object.
      • How to get the window size?    window.innerHeight, window.innerWidth
      • List the window properties and methods that you have used.    document, alert(), setInterval(), setTimeout()
      • What kind of events are triggered on window?    load, resize
    • There are other BOM objects - Navigator, Screen, History, Location.
  6. Dynamic style

  7. Learning outcomes